/*
 * Copyright (c) 2011 Auzingers
 * Created by Oui-IT
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.auzingers.docsorganizer.util;

import java.util.ArrayList;
import java.util.List;

/**
 * Utility class for manipulating collections.
 */
public final class CollectionUtil {

    /**
    * Hide constructor of utility class.
    */
    private CollectionUtil() {
        //hidden constructor
    }

    /**
     * Converts a list of type X that actually contains Ys into a list of type Y.
     * @param <X> source type
     * @param <Y> target type
     * @param source source list
     * @param resultType class of the target type
     * @return list of type Y
     * @throws IllegalArgumentException in case the list contains an element that isn't a of type Y.
     */
    @SuppressWarnings("unchecked")
    public static <X extends Object, Y extends Object> List<Y> convertList(List<X> source, Class<Y> resultType) {
        final List<Y> result = new ArrayList<Y>();
        for (final X sourceObj : source) {
            if (sourceObj == null) {
                result.add(null);
            } else if (sourceObj.getClass().equals(resultType)) {
                result.add((Y) sourceObj);
            } else {
                throw new IllegalStateException("Expected element of type " + resultType.getName());
            }
        }
        return result;
    }
}
